from rest_framework import serializers

from app.models import  User

class UserSerializer(serializers.ModelSerializer):
    #create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', required=False)

    class Meta:
        model = User
        #fields = '__all__'
        exclude = ['password'] 
        # exclude = ["user_permissions", "groups"]
        # fields = ['username', 'email','mobile','password']
        # list_display = ['username', 'email','mobile']  

    def validate(self, attrs):
        print(f"修改之前的字段{attrs}")
        print("原生创建")
        from django.contrib.auth import hashers
        attrs["password"] = hashers.make_password(attrs["password"])
        print("修改之后的字段")
        return attrs



# 创建用户注册序列化类
class UserRegistSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=10, min_length=3, error_messages={
        "required": "用户名必填"
    })
    # 写了write_only可以写入但是不展示
    password = serializers.CharField(max_length=10, min_length=3, write_only=True)
    password2 = serializers.CharField(max_length=10, min_length=3, write_only=True)
    mobile = serializers.CharField(max_length=15)

    def validate_password2(self, data):
        if data != self.initial_data["password"]:
            raise serializers.ValidationError("密码不一致111")
        else:
            return data

    # 校验密码,写了validate_password2和write_only=True这个方法基本都不用写了
    # def validate(self,attrs):
    #     # if attrs["password"]!=attrs["password2"]:
    #     #     raise serializers.ValidationError("密码不一致")
    #     del attrs["password2"]
    #     return attrs

    def create(self, validated_data):
        print(validated_data)
        # 使用User.objects.create密码不加密,使用User.objects.create_user密码加密
        # user_obj=User.objects.create(**validated_data),这个方法是将全部写入数据库,但是password2是多余的,要想办法去掉
        user_obj = User.objects.create_user(username=validated_data.get("username"),
                                            password=validated_data.get("password"),
                                            mobile=validated_data.get("mobile"))
        return user_obj


